/*
 * @Description: 创建移交归档单弹窗
 * @Author: Rfan
 * @Date: 2022-05-12 16:06:57
 * @LastEditTime: 2022-05-25 12:01:53
 */

import { Key, useEffect, useState } from 'react';
import { Button, Form, Input, Modal, Select, Space } from 'antd';
import type { FC } from 'react';
import { fetchATListByFondId } from '@/api/archivesType';
import { fetchFondsListByUnitId } from '@/api/fonds';
import { selectItemByKey } from '@/utils/list';
import { appState } from '@/store/mobx';
import { useTransferContext } from '../../../contexts/TransferContext';
import type { ICommonDialog } from '@/interfaces/global';

const { Option } = Select;

interface TransferFormProps extends ICommonDialog {}

const TransferForm: FC<TransferFormProps> = (props) => {
  console.log('UploadFloder', props.visible);
  const { visible, onClose } = props;
  const { addTransferFunc } = useTransferContext();
  const [form] = Form.useForm();

  // 部门列表
  // const [departmentList, setDepartmentList] = useState([]);
  // 全宗列表
  const [fondList, setFondList] = useState([]);
  // 档案类型列表
  const [atList, setAtList] = useState([]);
  // 档案类型加载状态
  const [atLoading, setAtLoading] = useState(false);
  // 选中的档案类型
  const [selectAT, setSelectAT] = useState(atList[0] || {});

  useEffect(() => {
    if (visible) {
      fetchFondsListByUnitId(appState.unitId).then((res) => {
        setFondList(res.data);
      });
    }
  }, [visible]);

  /**
   * @description: 关闭弹窗
   */
  const onCancel = () => {
    setSelectAT(atList[0] || {});
    form.resetFields();
    onClose();
  };

  /**
   * @description 切换全宗方法
   * @param {any} value 切换的全宗ID
   * @return {*}
   */
  const handleFondChange = (value: Key): void => {
    setAtLoading(true);
    fetchATListByFondId(value)
      .then((res) => {
        setAtList(res.data);
        res.data.length > 0 && setSelectAT(res.data[0]);
      })
      .finally(() => {
        setAtLoading(false);
      });
  };

  /**
   * @description 切换档案类型方法
   * @param {Key} value 切换的档案类型ID
   */
  const onATChange = (value: Key) => {
    setSelectAT(selectItemByKey(value, atList));
  };

  /**
   * @description 提交表单，触发onFinish方法
   */
  const submitFunc = () => {
    form.submit();
  };

  // 新增排序方法
  const onFinish = (values: any) => {
    values.archiveTypeName = selectAT.atName;
    values.fondsName = fondList.find((fond) => fond.id === values.fondId)?.fondName || '';

    addTransferFunc(values).then(() => {
      onCancel();
    });
  };

  return (
    <Modal
      title="创建移交申请单"
      visible={visible}
      width={600}
      destroyOnClose
      onCancel={onCancel}
      footer={[
        <Button key="close" onClick={onCancel}>
          取消
        </Button>,
        // <Button key="createAdd" type="primary">创建并添加档案</Button>,
        <Button
          key="create"
          type="primary"
          onClick={() => {
            submitFunc();
          }}
        >
          创建
        </Button>
      ]}
    >
      <Form form={form} labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} onFinish={onFinish}>
        <Form.Item name="title" label="标题" rules={[{ required: true }]}>
          <Input />
        </Form.Item>
        <Form.Item label="档案类型" rules={[{ required: true }]}>
          <Space>
            <Form.Item name="fondsId" noStyle>
              <Select placeholder="请选择全宗" style={{ width: 120 }} onChange={handleFondChange}>
                {fondList.map((fond) => (
                  <Option key={fond.id} value={fond.id}>
                    {fond.fondName}
                  </Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item name="archiveTypeId" noStyle>
              <Select
                value={selectAT?.id}
                loading={atLoading}
                placeholder="请选择档案类型"
                style={{ width: 120 }}
                onChange={onATChange}
              >
                {atList.map((item: any) => (
                  <Option key={item.id} value={item.id}>
                    {item.atName}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Space>
        </Form.Item>
        <Form.Item label="接收方">
          <Select placeholder="请选择部门" disabled></Select>
        </Form.Item>
        <Form.Item name="reamrk" label="移交说明">
          <Input.TextArea />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default TransferForm;
